package net.wicp.tams.common.others;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;

import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FreemarkUtil {
	private final static FreemarkUtil inst = new FreemarkUtil();

	private FreemarkUtil() {
	}

	public static FreemarkUtil getInst() {
		// 默认添加一个StringLoader
		StringTemplateLoader stringLoader = new StringTemplateLoader();
		TemplateLoader[] defaultLoads = new TemplateLoader[] { stringLoader };
		inst.addLoads(defaultLoads);
		return inst;
	}

	private Configuration cfg;
	private TemplateLoader[] curLoads;

	public synchronized void addLoads(TemplateLoader... templateLoader) {
		curLoads = ArrayUtils.addAll(curLoads, templateLoader);
		cfg = new Configuration(Configuration.VERSION_2_3_23);
		cfg.setDefaultEncoding("utf-8");
		MultiTemplateLoader mtl = new MultiTemplateLoader(curLoads);
		cfg.setTemplateLoader(mtl);
	}

	public TemplateLoader getLoad(int index) {
		return getLoad().getTemplateLoader(index);
	}

	public StringTemplateLoader getLoadStr() {
		return (StringTemplateLoader) getLoad(0);
	}

	public MultiTemplateLoader getLoad() {
		return (MultiTemplateLoader) cfg.getTemplateLoader();
	}

	public String getTempStr(String name) {
		try {
			Object source = getLoad().findTemplateSource(name);
			Reader reader = getLoad().getReader(source, "utf-8");
			String dest = IOUtils.toString(reader);
			return dest;
		} catch (Exception e) {
			log.error("获取模板错误", e);
			throw new RuntimeException("获取模板" + name + "错误");
		}
	}

	public long getTempLastTime(String name) {
		Object source;
		try {
			source = getLoad().findTemplateSource(name);
			return getLoad().getLastModified(source);
		} catch (IOException e) {
			log.error("获取模板错误", e);
			throw new RuntimeException("获取模板" + name + "错误");
		}
	}

	public Template getTemplate(String name) {
		try {
			return cfg.getTemplate(name);
		} catch (Exception e) {
			log.error("获取模板错误", e);
			throw new RuntimeException("获取模板" + name + "错误");
		}
	}

	public String doProcess(String name, Object dataModel) {
		Template template = getTemplate(name);
		StringWriter out = new StringWriter();
		try {
			template.process(dataModel, out);
			return out.toString();
		} catch (Exception e) {
			log.error("处理错误", e);
			throw new RuntimeException("处理错误,模板:" + name);
		}
	}

}
